<template>
  <el-card class="account_container">
    <el-row type="flex" justify="space-between" style="margin-bottom: 10px">
      <el-col>
        <el-button size="small" @click="handleBack">返回上一页</el-button>
        <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
      </el-col>
      <div>
        <!-- <el-button type="primary" @click="handleSubmit">提交</el-button> -->
      </div>
    </el-row>
    <div class="content">
      <el-card style="margin-bottom: 10px">
        <el-descriptions title="">
          <el-descriptions-item label="供应商" span="24">{{
            itemName
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card style="margin-bottom: 10px">
        <el-descriptions title="">
          <el-descriptions-item label="主账号" span="1">
            <div v-if="mainUser.userId">
              <div>{{ mainUser.userName }}</div>
              <span @click="updateMainAccount" class="el-button--text"
                >修改</span
              >
            </div>
            <span v-else @click="addMainAccountFn" class="el-button--text"
              >创建主账号</span
            >
          </el-descriptions-item>
          <el-descriptions-item
            label="主账号状态"
            span="1"
            v-if="mainUser.userId"
            ><el-switch
              @change="changeStatus(mainUser)"
              :value="mainUser.status == '0'"
            >
            </el-switch
          ></el-descriptions-item>
        </el-descriptions>
      </el-card>
      <div class="child_account" v-if="mainUser.userId">
        <div class="child_aside">子账号：</div>
        <div class="child_main">
          <el-form
            :model="childParams"
            ref="queryForm"
            size="mini"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label-width="40" label="姓名" prop="nickName">
              <el-input
                v-model="childParams.nickName"
                placeholder="请输入"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label-width="40" label="手机号" prop="phonenumber">
              <el-input
                v-model="childParams.phonenumber"
                placeholder="请输入"
                clearable
                :maxlength="11"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="addSunAccount"
                v-hasPermi="['system:designator:add']"
                >创建子账号</el-button
              >
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="childList">
            <el-table-column
              fixed="left"
              type="selection"
              width="55"
              align="center"
            />
            <el-table-column
              label="ID"
              width="55"
              align="center"
              prop="userId"
            />
            <el-table-column label="姓名" align="center" prop="nickName" />
            <el-table-column label="账号" align="center" prop="userName" />
            <el-table-column label="手机号" align="center" prop="phonenumber" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-switch
                  :value="scope.row.status == '0'"
                  @change="changeStatus(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              width="190px"
              fixed="right"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <!-- @click="handleUpdate(scope.row)" -->
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="updateSunAccount(scope.row)"
                  v-hasPermi="['system:designator:edit']"
                  >修改</el-button
                >
                <!-- @click="handleDelete(scope.row)" -->

                <el-popconfirm
                  title="确认删除此账号么？"
                  @confirm="handleDelete(scope.row)"
                >
                  <el-button
                    style="margin-left: 10px"
                    size="mini"
                    type="text"
                    slot="reference"
                    icon="el-icon-delete"
                    >删除</el-button
                  >
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 创建/修改主账号 -->
    <el-dialog
      :title="subAccountTitle"
      width="35%"
      :visible.sync="subAccountVisible"
    >
      <el-form
        :model="subFormModel"
        ref="subFormModel"
        label-width="100px"
        :rules="mainRules"
      >
        <el-form-item label="供应商">
          {{ itemName }}
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input
            placeholder="请输入"
            v-model="subFormModel.userName"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handelMainCencel">取 消</el-button>
        <el-button type="primary" @click="handelMainSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 创建/修改子账号 -->
    <el-dialog :title="sunTitle" :visible.sync="sunVisible" width="35%">
      <el-form
        :model="sunForm"
        :rules="sunRules"
        ref="sunForm"
        label-width="100px"
      >
        <el-form-item label="供应商">
          {{ itemName }}
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input placeholder="请输入" v-model="sunForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input placeholder="请输入" v-model="sunForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            placeholder="请输入"
            v-model="sunForm.phonenumber"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handelSunCencel">取 消</el-button>
        <el-button type="primary" @click="handelSunSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
  
  <script>
import { userTypeList } from "@/configEnum";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  listRole,
  deptTreeSelect,
  getRole,
  dataScope,
  changeRoleStatus,
} from "@/api/system/role";
import { listDept, listDeptChildren } from "@/api/system/dept";
import { addUser, getUser, updateUser, listUser } from "@/api/system/user";
import { validatePhoneNumber } from "@/utils";
import {
  listDesignator,
  getDesignator,
  delDesignator,
  addDesignator,
  updateDesignator,
} from "@/api/service/main";
import {
  supplierAccount,
  addMainAccount,
  changeAccount,
  addSunAccount,
  deleteSunAccount,
} from "@/api/service/purchase/supplier.js";
export default {
  components: {},
  data() {
    return {
      itemName: "",
      mainAccountIsopen: false, //主账号是否开启
      // 查询参数
      childParams: {
        id: null,
        name: null,
        oneCategoryId: null,
        twoCategoryId: null,
        threeCategoryId: null,
      },
      originName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限",
        },
        {
          value: "2",
          label: "自定数据权限",
        },
        {
          value: "3",
          label: "本部门数据权限",
        },
        {
          value: "4",
          label: "本部门及以下数据权限",
        },
        {
          value: "5",
          label: "仅本人数据权限",
        },
      ],
      deptOptions: [],
      // 菜单列表
      menuOptions: [],
      mainRules: {
        userName: [
          {
            required: true,
            message: "请输入账号",
            trigger: "change",
          },
        ],
      },
      rules: {
        nickName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择机构",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        phonenumber: validatePhoneNumber(),
        userName: [
          {
            required: true,
            message: "请输入账号",
            trigger: "change",
          },
        ],
        expireTime: [
          {
            required: true,
            message: "请选择账号有效期",
            trigger: "change",
          },
        ],
        roleIds: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
      },
      sunRules: {
        nickName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
        ],
        userName: [
          {
            required: true,
            message: "请输入账号",
            trigger: "change",
          },
        ],
        phonenumber: validatePhoneNumber(),
      },
      // 产品--主标号表格数据
      designatorList: [],
      subAccountTitle: "创建供应商主账号",
      sunTitle: "",
      sunVisible: false,
      subFormModel: {
        userName: undefined,
      },
      sunForm: {},
      subAccountVisible: false,
      subAccountList: [],
      userTypeList,
      formModel: {
        expireTime: undefined,
        userInfoId: undefined,
        userType: 1,
        nickName: undefined,
        phonenumber: undefined,
        idNumber: undefined,
        userName: undefined,
        postName: undefined,
        address: undefined,
        birthday: undefined,
        status: "0",
        orgId: "", // 机构
        deptId: "", // 部门
        accountDate: undefined,
        remark: undefined,
        sex: "1",
        roleIds: [],
      },
      dialogVisible: false,
      roleList: [], // 角色列表
      orgList: [], // 机构列表
      deptList: [], // 部门列表
      deptExpand: true,
      deptNodeAll: false,
      total: 0,
      // 遮罩层
      loading: true,
      // 主账号信息
      mainUser: {},
      childList: [],
    };
  },
  watch: {},
  methods: {
    // 修改主账号状态
    changeStatus(item) {
      var _this = this;
      const form = { ...item };
      // 改变状态
      form.status = item.status == "0" ? 1 : 0;
      changeAccount(form).then((res) => {
        let { code } = res;
        if (code == "200") {
          _this.$message.success("状态修改成功");
          _this.getUserInfo(_this.userId);
        } else {
          _this.$message.error("状态修改失败");
        }
      });
    },
    // 获取账号信息
    getUserInfo(userId) {
      var _this = this;
      if (userId) {
        supplierAccount(userId).then((response) => {
          console.log(response);
          if (response.code == "200") {
            if (response.data) {
              let { childUsers, user } = response.data;
              if (user && user.userId) {
                _this.mainUser = user;
                _this.childList = childUsers || [];
                _this.loading = false;
              }
            }
          } else {
            this.$message.error("获取账号信息失败");
          }
        });
      }
    },
    // 主账号dialog取消
    handelMainCencel() {
      this.$refs.subFormModel.resetFields();
      this.subAccountVisible = false;
    },
    // 主账号确定
    handelMainSubmit() {
      this.$refs.subFormModel.validate((valid) => {
        if (valid) {
          this.handleMainAdd();
        } else {
          return false;
        }
      });
    },
    // 子账号dialog取消
    handelSunCencel() {
      this.$refs.sunForm.resetFields();
      this.sunVisible = false;
    },
    // 主账号调用
    handleMainAdd() {
      var _this = this;
      if (this.subFormModel.userId) {
        changeAccount(this.subFormModel).then((res) => {
          let { code } = res;
          if (code == "200") {
            _this.$message.success("主账号修改成功");
            _this.handelMainCencel();
            _this.getUserInfo(_this.userId);
          } else {
            _this.$message.error("主账号修改失败");
          }
        });
      } else {
        addMainAccount({
          ...this.subFormModel,
          supplierId: this.userId,
        }).then((res) => {
          let { code } = res;
          if (code == "200") {
            _this.$message.success("主账号添加成功");
            _this.handelMainCencel();
            _this.getUserInfo(_this.userId);
          } else {
            _this.$message.error("主账号添加失败");
          }
        });
      }
    },
    // 子账号确定
    handelSunSubmit() {
      this.$refs.sunForm.validate((valid) => {
        if (valid) {
          this.handleSunAdd();
        } else {
          return false;
        }
      });
    },
    // 子账号调用
    handleSunAdd() {
      var _this = this;
      if (this.sunForm.userId) {
        changeAccount(this.sunForm).then((res) => {
          let { code } = res;
          if (code == "200") {
            _this.$message.success("主账号修改成功");
            _this.handelSunCencel();
            _this.getUserInfo(_this.userId);
          } else {
            _this.$message.error("主账号修改失败");
          }
        });
      } else {
        addSunAccount({
          ...this.sunForm,
          supplierId: this.userId,
        }).then((res) => {
          let { code } = res;
          if (code == "200") {
            _this.$message.success("主账号添加成功");
            _this.handelSunCencel();
            _this.getUserInfo(_this.userId);
          } else {
            _this.$message.error("主账号添加失败");
          }
        });
      }
    },
    // 创建主账号
    handelCreatMain() {},
    handleCardChange(val) {
      this.originName = "";
    },
    // 选择姓名弹框确认
    handleOnSubmit(userInfoId, name) {
      console.log(name);
      this.originName = name;
      this.formModel = { ...this.formModel, userInfoId };
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleValidateSuccess();
        } else {
          return false;
        }
      });
    },
    handleValidateSuccess() {
      if (!this.userId) {
        addUser({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      } else {
        updateUser({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      }
    },
    handleOkToLink() {
      this.$modal.msgSuccess("操作成功");
      // this.getUserInfo(this.userId);
      this.$router.push({
        path: "/system/user",
      });
    },
    handleOrg() {
      // 获取部门列表
      listDeptChildren({
        orgId: this.formModel.orgId,
      }).then((res) => {
        console.log(res);
        this.deptList = res.data;
      });
    },
    /** 查询产品--主标号列表 */
    getSunList() {
      this.loading = true;
      listDesignator(this.childParams).then((response) => {
        this.designatorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleBack() {
      this.$router.push({
        path: "/purchase/supplier/index",
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.getSunList();
    },
    removeSubAccount(row) {
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加主账号
    addMainAccountFn() {
      this.subAccountVisible = true;
    },
    // 修改主账号
    updateMainAccount() {
      this.subAccountVisible = true;
      this.subAccountTitle = "修改供应商主账号";
      this.subFormModel = this.mainUser;
    },
    // 添加子账号
    addSunAccount() {
      this.sunVisible = true;
    },
    // 修改子账号
    updateSunAccount(row) {
      this.sunVisible = true;
      this.sunTitle = "修改子账号";
      this.sunForm = {
        ...row,
      };
    },
    // 删除账号
    handleDelete(val) {
      console.log(val);
      deleteSunAccount(val.userId).then((response) => {});
    },
    handleSelectName() {
      this.dialogVisible = true;
    },
  },
  created() {
    this.userId = this.$route.query.id;
    this.itemName = this.$route.query.name;
    if (this.userId) {
      this.getUserInfo(this.userId);
    }
    // this.getSunList();
  },
  computed: {
    title() {
      return !this.$route?.query?.id ? "供应商账号管理" : "供应商账号管理";
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.tree-border {
  width: 200px;
}
.add_account {
  display: flex;
  align-items: center;
  .el-button {
    padding: 0;
    margin-left: 10px;
  }
  .el-switch {
    margin-left: 10px;
  }
}
.el-button--text {
  cursor: pointer;
}
.account_container {
  height: 100%;
  .child_account {
    display: flex;
    flex-direction: row;
    width: 100%;
    .child_aside {
      width: 70px;
      text-align: center;
      font-weight: normal;
      font-size: 14px;
      padding-top: 10px;
      color: #606266;
    }
    .child_main {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 10px;
      box-sizing: border-box;
      flex: 1;
      overflow: hidden;
      border-radius: 4px;
      border: 1px solid #e6ebf5;
      background-color: #ffffff;
    }
  }
  .content {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
  }
}
</style>
  